#!/usr/bin/env python
import gtk
import gtk.glade
import sys,os,re,string

class AskPass:

	def on_passwd_key_press_event(self,widget,event):
		if event.keyval==65293: #Is enter key
			self.on_ok_clicked()

	def on_ok_clicked(self,widget=None):
		self.success=True
		self.password=self.passwd.get_text()
		self.window.hide_all()		
		gtk.main_quit()
		
	def on_cancel_clicked(self,widget=None):
		md = gtk.MessageDialog(self.window,
				       gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, 
				       gtk.BUTTONS_YES_NO, "Are you sure to quit?")
		a=md.run()
		md.destroy()

		if a==gtk.RESPONSE_YES:
			self.success=False
			self.window.hide_all()			
			gtk.main_quit()

	def __init__(self, prompttext):

		#Set the Glade file
		self.gladefile = sys.path[0]+"/askpass.glade"  
	        self.wTree = gtk.glade.XML(self.gladefile) 
		#Get the Main Window, and connect the "destroy" event
		self.window = self.wTree.get_widget("askpasswindow")

		dic = {
			"on_passwd_key_press_event" : self.on_passwd_key_press_event,
			"on_ok_clicked":self.on_ok_clicked,
			"on_cancel_clicked":self.on_cancel_clicked,
			}

		self.wTree.signal_autoconnect(dic)


		if (self.window):
			self.window.connect("destroy", self.on_mainwindow_destroy)
			
		self.passwd=self.wTree.get_widget("passwd")

		self.ok=self.wTree.get_widget("ok")

		if not prompttext is None:
			self.textmsg=self.wTree.get_widget("textmsg")
			self.textmsg.get_buffer().set_text(prompttext)
			
	def on_mainwindow_destroy(self,widget):
		self.success=False
		self.window.hide_all()
		gtk.main_quit()

def doAskPass(prompttext=None):
	ap = AskPass(prompttext)
	gtk.main()
	if ap.success:
		return (True,ap.password)
	return (False,None)
	
if __name__ == "__main__":

	if len(sys.argv)>1:
		prompttext=sys.argv[1]
	else:
		prompttext=None
	
	(status,password)=doAskPass(prompttext)
	
	if status:
		print password
		sys.exit(0)

	sys.exit(-1)
	
